package com.iocup.keybastion.core.impl;

import com.iocup.keybastion.common.AuthConstant;
import com.iocup.keybastion.configuration.SecurityProperties;
import com.iocup.keybastion.context.SecurityContextHolder;
import com.iocup.keybastion.context.WebContextHolder;
import com.iocup.keybastion.core.LogoutLogic;
import com.iocup.keybastion.core.client.Client;
import com.iocup.keybastion.core.client.ClientFinder;
import com.iocup.keybastion.exception.AuthenticationException;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * @author xyjxust
 * @create 2022/3/4 16:54
 **/
public class DefaultLogoutLogic implements LogoutLogic {

    private ClientFinder clientFinder;

    /**
     * 配置类
     */
    private SecurityProperties securityProperties;

    public DefaultLogoutLogic(ClientFinder clientFinder,SecurityProperties securityProperties){
        this.clientFinder = clientFinder;
        this.securityProperties = securityProperties;
    }

    @Override
    public void logout(String loginName, String clientName,String device) {
        clientName = findClientName(SecurityContextHolder.getContext().getWebContextHolder());
        device = getDevice(device);
        Optional<Client> optionalClient = clientFinder.find(clientName);
        if (!optionalClient.isPresent()) {
            throw new AuthenticationException("clientName错误");
        }
        optionalClient.get().doLogoutAction(SecurityContextHolder.getContext().getWebContextHolder()
                , loginName,device , null);

    }


    private String findClientName(WebContextHolder contextHolder) {
        Optional<String> clientName = contextHolder.getRequestHeader(AuthConstant.LOGIN_CLIENT_NAME);
        if (!clientName.isPresent()) {
            clientName = contextHolder.getRequestParameter(AuthConstant.LOGIN_CLIENT_NAME);
        }
        if (!clientName.isPresent()) {
            clientName = Optional.of(this.securityProperties.getClient());
        }
        return clientName.get();
    }

    private String getDevice(String device) {
        if (StringUtils.isNotBlank(device)) {
            return device;
        }
        WebContextHolder webContextHolder = SecurityContextHolder.getContext().getWebContextHolder();
        if (webContextHolder == null) {
            throw new SecurityException("未查找到请求上下文");
        }
        return webContextHolder.getRequestHeader(AuthConstant.DEVICE_NAME, AuthConstant.DEFAULT_DEVICE_NAME);

    }
}
